package com.baitai.system.service.impl;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baitai.common.utils.CommonUtils;
import com.baitai.common.utils.DateUtils;
import com.baitai.system.domain.*;
import com.baitai.system.domain.vo.Express100DTO;
import com.baitai.system.domain.vo.LogisticsInfoDTO;
import com.baitai.system.mapper.*;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.api.Subscribe;
import com.kuaidi100.sdk.contant.ApiInfoConstant;
import com.kuaidi100.sdk.contant.CompanyConstant;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.*;
import com.kuaidi100.sdk.utils.SignUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;

import com.baitai.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.baitai.system.service.IProductOrdersService;

/**
 * 商品订单Service业务层处理
 * 
 * @author xx
 * @date 2024-07-21
 */
@Service
public class ProductOrdersServiceImpl implements IProductOrdersService 
{
    @Autowired
    private ProductOrdersMapper productOrdersMapper;
    @Autowired
    private ShippingRecordMapper shippingRecordMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private SysUseConsigneeInfoMapper sysUseConsigneeInfoMapper;
    @Value("${kuaidi100.key}")
    private String key;

    @Value("${kuaidi100.customer}")
    private String customer;

    /**
     * 查询商品订单
     * 
     * @param orderId 商品订单主键
     * @return 商品订单
     */
    @Override
    public ProductOrders selectProductOrdersByOrderId(Long orderId)
    {
        ProductOrders productOrders = productOrdersMapper.selectProductOrdersByOrderId(orderId);
        for (ProductOrderDetails details : productOrders.getProductOrderDetailsList()) {
            details.setProductInfo(productInfoMapper.selectProductInfoById(details.getProductId()));
        }
        productOrders.setSysUseConsigneeInfo(sysUseConsigneeInfoMapper.selectSysUseConsigneeInfoById(productOrders.getAddressId()));
        return productOrders;
    }

    /**
     * 查询商品订单列表
     * 
     * @param productOrders 商品订单
     * @return 商品订单
     */
    @Override
    public List<ProductOrders> selectProductOrdersList(ProductOrders productOrders)
    {
        return productOrdersMapper.selectProductOrdersList(productOrders);
    }

    /**
     * 新增商品订单
     * 
     * @param productOrders 商品订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertProductOrders(ProductOrders productOrders)
    {
        productOrders.setCreateTime(DateUtils.getNowDate());
        int rows = productOrdersMapper.insertProductOrders(productOrders);
        insertProductOrderDetails(productOrders);
        return rows;
    }

    /**
     * 修改商品订单
     * 
     * @param productOrders 商品订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateProductOrders(ProductOrders productOrders)
    {
        productOrders.setUpdateTime(DateUtils.getNowDate());
        productOrdersMapper.deleteProductOrderDetailsByOrderId(productOrders.getOrderId());
        insertProductOrderDetails(productOrders);
        if(StringUtils.isNotNull(productOrders.getShippingNumber())&&StringUtils.isNotNull(productOrders.getShippingCompany())){
            //todo 订阅快递单号
            SysUseConsigneeInfo consigneeInfo = sysUseConsigneeInfoMapper.selectSysUseConsigneeInfoById(productOrders.getAddressId());
            try {
                subscribe(productOrders.getOrderId(),productOrders.getShippingCompany(),productOrders.getShippingNumber(),consigneeInfo.getConsigneePhone());
            }catch (Exception e){
                System.out.println("订阅物流信息失败");
            }
        }
        return productOrdersMapper.updateProductOrders(productOrders);
    }

    /**
     * 批量删除商品订单
     * 
     * @param orderIds 需要删除的商品订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProductOrdersByOrderIds(Long[] orderIds)
    {
        productOrdersMapper.deleteProductOrderDetailsByOrderIds(orderIds);
        return productOrdersMapper.deleteProductOrdersByOrderIds(orderIds);
    }

    /**
     * 删除商品订单信息
     * 
     * @param orderId 商品订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProductOrdersByOrderId(Long orderId)
    {
        productOrdersMapper.deleteProductOrderDetailsByOrderId(orderId);
        return productOrdersMapper.deleteProductOrdersByOrderId(orderId);
    }

    /**
     * 新增订单明细信息
     * 
     * @param productOrders 商品订单对象
     */
    public void insertProductOrderDetails(ProductOrders productOrders)
    {
        List<ProductOrderDetails> productOrderDetailsList = productOrders.getProductOrderDetailsList();
        Long orderId = productOrders.getOrderId();
        if (StringUtils.isNotNull(productOrderDetailsList))
        {
            List<ProductOrderDetails> list = new ArrayList<ProductOrderDetails>();
            for (ProductOrderDetails productOrderDetails : productOrderDetailsList)
            {
                productOrderDetails.setOrderId(orderId);
                list.add(productOrderDetails);
            }
            if (list.size() > 0)
            {
                productOrdersMapper.batchProductOrderDetails(list);
            }
        }
    }

    /**
     * 查询商品订单列表
     *
     * @param productOrders 商品订单
     * @return 商品订单
     */
    @Override
    public List<ProductOrders> appList(ProductOrders productOrders)
    {
        return productOrdersMapper.appList(productOrders);
    }

    @Override
    public void findOrder(Long orderId) {
        ProductOrders orders = productOrdersMapper.selectProductOrdersByOrderId(orderId);
        Express100DTO response = null;
        try {
            QueryTrackReq queryTrackReq = new QueryTrackReq();
            QueryTrackParam queryTrackParam = new QueryTrackParam();
            queryTrackParam.setCom(orders.getShippingCompany());
            queryTrackParam.setNum(orders.getShippingNumber());
            String param = new Gson().toJson(queryTrackParam);

            queryTrackReq.setParam(param);
            queryTrackReq.setCustomer(customer);
            queryTrackReq.setSign(SignUtils.querySign(param ,key,customer));

            IBaseClient baseClient = new QueryTrack();
            HttpResult execute = baseClient.execute(queryTrackReq);
            // 对返回的数据进行反序列化处理
            Gson gson = new Gson();
            String responseBody = execute.getBody();
            response = gson.fromJson(responseBody, Express100DTO.class);

            for (LogisticsInfoDTO datum : response.getData()) {
                ShippingRecord shippingRecord = new ShippingRecord();
                shippingRecord.setTime(DateUtils.parseDate(datum.getTime()));
                shippingRecord.setFtime(DateUtils.parseDate(datum.getFtime()));
                shippingRecord.setContext(datum.getContext());
                shippingRecord.setOrderId(orderId);
                shippingRecordMapper.insertShippingRecord(shippingRecord);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert response != null;
        System.out.println(response.getData());
    }
    private void subscribe(Long orderId,String shippingCompany,String shippingNumber,String phone) throws Exception{
        SubscribeParameters subscribeParameters = new SubscribeParameters();
        subscribeParameters.setCallbackurl("http://taishanbaitai.com/system/productOrders/callback/"+orderId);
        subscribeParameters.setPhone(phone);

        SubscribeParam subscribeParam = new SubscribeParam();
        subscribeParam.setParameters(subscribeParameters);
        subscribeParam.setCompany(shippingCompany);
        subscribeParam.setNumber(shippingNumber);
        subscribeParam.setKey(key);

        SubscribeReq subscribeReq = new SubscribeReq();
        subscribeReq.setSchema(ApiInfoConstant.SUBSCRIBE_SCHEMA);
        subscribeReq.setParam(new Gson().toJson(subscribeParam));

        IBaseClient subscribe = new Subscribe();
        System.out.println(subscribe.execute(subscribeReq));
    }

    @Transactional
    @Override
    public void callback(Long orderId, JSONObject express100DTO) {
        JSONObject param = express100DTO.getJSONObject("param");
        JSONObject lastResult = param.getJSONObject("lastResult");
        JSONArray data = lastResult.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject shipping = data.getJSONObject(i);
            ShippingRecord shippingRecord = new ShippingRecord();
            shippingRecord.setTime(DateUtils.parseDate(shipping.getString("time")));
            shippingRecord.setFtime(DateUtils.parseDate(shipping.getString("ftime")));
            shippingRecord.setContext(shipping.getString("context"));
            shippingRecord.setOrderId(orderId);
            shippingRecordMapper.insertShippingRecord(shippingRecord);
        }
        ProductOrders orders = productOrdersMapper.selectProductOrdersByOrderId(orderId);
        orders.setShippingStatus(lastResult.getString("state"));
        productOrdersMapper.updateProductOrders(orders);
//        for (LogisticsInfoDTO datum : express100DTO.getData()) {
//            ShippingRecord shippingRecord = new ShippingRecord();
//            shippingRecord.setTime(DateUtils.parseDate(datum.getTime()));
//            shippingRecord.setFtime(DateUtils.parseDate(datum.getFtime()));
//            shippingRecord.setContext(datum.getContext());
//            shippingRecord.setOrderId(orderId);
//            shippingRecordMapper.insertShippingRecord(shippingRecord);
//        }
    }

    @Override
    public void updateProductOrdersStatus(JSONObject jsonString) {
        String orderNumber = jsonString.getString("out_trade_no");
        ProductOrders orders = productOrdersMapper.selectProductOrdersByOrderNumber(orderNumber);
        orders.setPaymentStatus("1");
        productOrdersMapper.updateProductOrders(orders);
    }

    @Override
    public List<ProductOrders> verify(Date start, Date end, Long userId) {
        return productOrdersMapper.verify(start,end,userId);
    }
}
